﻿#!/usr/bin/env python
#coding:utf-8
from probe.core.level import *
import time
def get_cpu_info(args):
    '''监控CPU使用率'''
    fd = open("/proc/stat", 'r') 
    lines = fd.readlines()
    fd.close()
    split = filter(lambda x:x is not ' ', (x for x in lines[1].split()))
    total = int(split[1]) + int(split[2])+ int(split[3])+ int(split[4])+ \
          int(split[5])+ int(split[6])+ int(split[7])
    idle = int(split[4])
    time.sleep(2)
    fd = open("/proc/stat", 'r') 
    lines2 = fd.readlines()
    fd.close()
    split2 = filter(lambda x:x is not ' ', (x for x in lines2[1].split()))
    total2 = int(split2[1]) + int(split2[2]) + int(split2[3])+ int(split2[4])+ \
           int(split2[5])+ int(split2[6])+ int(split2[7])
    idle2 = int(split2[4])
    usage = 100 - (idle2-idle)*100/(total2-total)

    if usage >= args.get('WarningData'):
        return WarningData({'CPU使用率': [float(usage), '%']})
    return InfoData({'CPU使用率': [float(usage), '%']})

if __name__ == '__main__':
    print get_cpu_info({'WarningData': 40})

